using System;
using System.Data;
using System.Data.Common;
using Rogan.Utility.Common;

namespace Rogan.Data
{
	public class DbTrans : IDisposable
	{
		private bool isCommitOrRollback;
		private bool isClose;
		public DbTransaction Trans
		{
			get;
			private set;
		}
		public DbConnection Connection
		{
			get;
			private set;
		}
		public IsolationLevel IsolationLevel
		{
			get;
			private set;
		}
		public DbTrans(DbTransaction trans)
		{
			Guard.IsNotNull(trans, "trans");
			Trans = trans;
			Connection = trans.Connection;
			if (Connection.State != ConnectionState.Open)
			{
				Connection.Open();
			}
		}
		public void Commit()
		{
			Trans.Commit();
			isCommitOrRollback = true;
			Close();
		}
		public void Rollback()
		{
			Trans.Rollback();
			isCommitOrRollback = true;
			Close();
		}
		public static implicit operator DbTransaction(DbTrans dbTrans)
		{
			return dbTrans.Trans;
		}
		public void Close()
		{
			if (isClose)
			{
				return;
			}
			if (!isCommitOrRollback)
			{
				isCommitOrRollback = true;
				Trans.Rollback();
			}
			if (Connection.State != ConnectionState.Closed)
			{
				Connection.Close();
			}
			Trans.Dispose();
			isClose = true;
		}
		public void Dispose()
		{
			Close();
		}
	}
}
